package org.ting.e_commerce.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.ting.e_commerce.model.Result;
import org.ting.e_commerce.model.Store;
import org.ting.e_commerce.service.StoreService;

import java.util.List;

@RestController
@RequestMapping("/store")
public class StoreController {
    @Autowired
    StoreService storeService;
    @RequestMapping("/addStore")
    public Result<?> addStore(Store store) {
        //检测店铺名称是否被使用
        Store dbStore = storeService.selectStoreByStoreName(store.getStoreName());
        if(dbStore != null) {
            return Result.fail("该店铺名称已经被注册");
        }
        if(storeService.addStore(store)) {
            return Result.success("success");
        }
        return Result.fail("未知错误请联系管理员");
    }

    @RequestMapping("/selectStoreOfUser")
    public List<Store> selectStoreOfUser(Integer userId) {
        return storeService.selectByUserId(userId);
    }

    @RequestMapping("/selectById")
    public Result<?> selectById(int storeId) {
        Store ret = storeService.selectById(storeId);
        if(ret == null) {
            return Result.fail("未查询到该店铺");
        }
        return  Result.success(ret);
    }

    @RequestMapping("/selectByUserIdAndStoreId")
    public Result<?> selectByUserIdAndStoreId(int userId, int storeId) {
        Store ret = storeService.selectByUserIdAndStoreId(userId, storeId);
        if(ret == null) {
            return Result.fail("未查询到该店铺");
        }
        return  Result.success(ret);
    }

    @RequestMapping("/updateStore")
    public Result<?> updateStoreByStoreId(Store store) {
        //检查店铺是否存在
        if(storeService.selectByUserIdAndStoreId(store.getUserId(), store.getStoreId()) == null) {
            return Result.fail("店铺不存在或无操作权限");
        }
        if(storeService.updateStoreByStoreId(store)) {
            return Result.success("success");
        }
        return Result.fail("未知错误");
    }
}
